package com.healthlink.appcloudcalllib.utils;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.healthlink.appcloudcalllib.CloudCallManager;
import com.healthlink.appcloudcalllib.callback.ICallMessage;
import com.healthlink.appcloudcalllib.callback.ICallInCallback;
import com.healthlink.appcloudcalllib.callback.ICallOutCallback;
import com.healthlink.appcloudcalllib.callback.IGoonCallback;
import com.healthlink.appcloudcalllib.callback.IInitCallBack;
import com.healthlink.appcloudcalllib.callback.IResultCallback;
import com.healthlink.appcloudcalllib.common.MessageType;
import com.healthlink.appcloudcalllib.databean.AcceptCallinData;
import com.healthlink.appcloudcalllib.databean.CallOutBackData;
import com.healthlink.appcloudcalllib.databean.CallOutToSdkData;
import com.healthlink.appcloudcalllib.net.OKCallback;
import com.healthlink.appcloudcalllib.net.OkUtils;

import java.util.LinkedHashMap;

import io.agora.rtc2.ChannelMediaOptions;
import io.agora.rtc2.Constants;
import io.agora.rtc2.IRtcEngineEventHandler;
import io.agora.rtc2.LeaveChannelOptions;
import io.agora.rtc2.RtcEngine;
import io.agora.rtc2.RtcEngineConfig;

/**
 * 通话封装类
 */
public class CallUtils {
    Context context;
    ICallMessage iCallMessage;

    RtcEngine  mRtcEngine;
    public static volatile CallUtils agoraUtils;
    private CallUtils(){}

    public static CallUtils getInstance(){
        if (agoraUtils==null){
            synchronized (CallUtils.class){
                if (agoraUtils==null){
                    agoraUtils=new CallUtils();
                }
            }

        }
        return  agoraUtils;
    }
    public void init(Context context, ICallMessage iCallMessage){
        this.context=context;
        this.iCallMessage = iCallMessage;
        initAgoraSdk(context,"3d5124fc326a4a678ae05aa4000b4dfb");
    }


    /**
     * 初始化SDK
     * @param context
     * @param appid
     */
    public RtcEngine initAgoraSdk(Context context, String appid){
        IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
            @Override
            // 监听频道内的远端主播，获取主播的 uid 信息。
            public void onUserJoined(int uid, int elapsed) {
                iCallMessage.initSuccess();

            }

            @Override
            public void onUserOffline(int uid, int reason) {
                super.onUserOffline(uid, reason);

            }

            @Override
            public void onLeaveChannel(RtcStats stats) {
                super.onLeaveChannel(stats);

            }
        };
        RtcEngineConfig config = new RtcEngineConfig();
        config.mContext = context;
        config.mAppId = appid;
        config.mEventHandler = mRtcEventHandler;
        try {
              mRtcEngine = RtcEngine.create(config);
            return mRtcEngine;
        }catch (Exception exception){
            Out.out("sw初始化失败："+exception.getMessage());
            exception.printStackTrace();
            return null;
        }
    }
    /**
     * 获取上一次未完成的通话
     * @param accessToken
     * @param appId
     * @param productId
     * @param iInitCallBack
     */
    public void getLastCall(String accessToken, String appId, String productId, IInitCallBack iInitCallBack){
        LinkedHashMap param=new LinkedHashMap<String,String>();
        param.put("appId",appId);
        param.put("productId",productId);
        param.put("serialNumber", com.healthlink.appcloudcalllib.common.Constants.sn);
        Out.out("获取lastAAA");
        OkUtils.performByJsonArray(context,com.healthlink.appcloudcalllib.common.Constants.GetHistoryCall,accessToken,param,2,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                Out.out("last返回："+str);
                try {

                    JSONObject dataObj= JSONObject.parseObject(str);
                    String roomId="";
                    try {
                        roomId=dataObj.getString("roomID");
                    }catch (Exception exception){

                    }


                    if (TextUtils.isEmpty(roomId)){
                        iInitCallBack.initResult(0,"");
                    }else{
                        iInitCallBack.initResult(1,str);
                    }


                }catch (Exception exception){exception.printStackTrace();}
            }

            @Override
            public void Eorror(int code) {
                super.Eorror(code);
                Out.out("last返回EEE："+code);
                iInitCallBack.initResult(code,"");

            }
        });




    }
    /**
     * 拨号
     * @param accessToken
     * @param appId
     * @param productId
     * @param phoneOutCallBackListenner
     */
    public void careateRoom(String accessToken, String appId, String productId, ICallOutCallback phoneOutCallBackListenner){

        Out.out("正式请求拨号");
        LinkedHashMap param=new LinkedHashMap<String,String>();
        param.put("appId",appId);
        param.put("productId",productId);
        param.put("serialNumber", com.healthlink.appcloudcalllib.common.Constants.sn);
        OkUtils.performByJsonArray(context,com.healthlink.appcloudcalllib.common.Constants.RequestCallOut,accessToken,param,2,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                com.healthlink.appcloudcalllib.common.Constants.logs.add("正式请求拨号返回："+System.currentTimeMillis());
                try {
                    Out.out("请求拨号返回："+str);
                CallOutBackData callOutBackData= JSON.parseObject(str,CallOutBackData.class);
                ChannelMediaOptions options = new ChannelMediaOptions();
                // 设置频道场景为 BROADCASTING。
                options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING;
                // 将用户角色设置为 BROADCASTER。
                options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER;

                mRtcEngine.joinChannel(callOutBackData.token,callOutBackData.roomID,Integer.parseInt(callOutBackData.uid),options);
                    com.healthlink.appcloudcalllib.common.Constants.logs.add("加入声网："+System.currentTimeMillis());

                    CallOutToSdkData callOutToSdkData=new CallOutToSdkData();
                callOutToSdkData.callee=callOutBackData.callee;
                callOutToSdkData.caller=callOutBackData.caller;
                callOutToSdkData.roomId=callOutBackData.roomID;


                phoneOutCallBackListenner.onCallingCreate(0,JSON.toJSONString(callOutToSdkData));
                    com.healthlink.appcloudcalllib.common.Constants.logs.add("拨号成功回调APP："+System.currentTimeMillis());

                }catch (Exception exception){exception.printStackTrace();}
            }

            @Override
            public void Eorror(int code) {
                super.Eorror(code);

                phoneOutCallBackListenner.onCallingCreate(code,"");
            }
        });




    }
    /**
     * 拨号
     * @param accessToken
     * @param appId
     * @param productId
     * @param phoneOutCallBackListenner2
     */
    public void clearHistory(String accessToken, String appId, String productId, ICallOutCallback phoneOutCallBackListenner2){

        LinkedHashMap param=new LinkedHashMap<String,String>();
        param.put("appId",appId);
        param.put("productId",productId);
        param.put("serialNumber", com.healthlink.appcloudcalllib.common.Constants.sn);
        OkUtils.performByJsonArray(context,com.healthlink.appcloudcalllib.common.Constants.ClearHistroyCall,accessToken,param,2,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                try {
                    phoneOutCallBackListenner2.onCallingCreate(888,"");
                }catch (Exception exception){exception.printStackTrace();}
            }

            @Override
            public void Eorror(int code) {
                super.Eorror(code);
                Out.out2("错误代码："+code);
                phoneOutCallBackListenner2.onCallingCreate(code,"");
            }
        });




    }
    /**
     * 接通来电
     * @param accessToken
     * @param roomId
     * @param caller
     * @param callee
     * @param iCallInCallback
     */
    public void joinTORoom(Context context, String accessToken, String roomId, String caller, String callee, ICallInCallback iCallInCallback){

        LinkedHashMap param=new LinkedHashMap<String,String >();
        param.put("callee",callee);
        param.put("caller",caller);
        param.put("roomId",roomId);
        param.put("serialNumber",Out.getAndroidId(context));
        OkUtils.performByJsonArray(context, com.healthlink.appcloudcalllib.common.Constants.AcceptCallin,accessToken,param,2,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);

                AcceptCallinData acceptCallinData=JSON.parseObject(str,AcceptCallinData.class);
                ChannelMediaOptions options = new ChannelMediaOptions();
                // 设置频道场景为 BROADCASTING。
                options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING;
                // 将用户角色设置为 BROADCASTER。
                options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER;
                mRtcEngine.joinChannel(acceptCallinData.token,roomId,Integer.parseInt(acceptCallinData.uid),options);
                iCallInCallback.onCallInState(0);
            }

            @Override
            public void Eorror(int code) {
                super.Eorror(code);
                iCallInCallback.onCallInState(code);
            }
        });


    }
    /**
     * 挂断来电
     * @param accessToken
     * @param iResultCallback
     * @param roomId
     * @param  type 1 通话中挂断 0 拒绝
     */
    public void hangUp(Context context, String accessToken, String roomId, int type, IResultCallback iResultCallback){

        LinkedHashMap param=new LinkedHashMap<String,String >();
        param.put("roomId",roomId);
        param.put("serialNumber",Out.getAndroidId(context));
        OkUtils.performByJsonArray(context, com.healthlink.appcloudcalllib.common.Constants.HangUp,accessToken,param,2,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);

                if (type==1){
                    try {
                        mRtcEngine.leaveChannel();
                    }catch (Exception ex){}
                }
                iResultCallback.onCallback(0);
            }
            @Override
            public void Eorror(int code) {
                super.Eorror(code);
                iResultCallback.onCallback(code);
            }
        });

    }

    /**
     * 离开通话
     */
    public void levalChanel(){
        try {
          mRtcEngine.leaveChannel();
        }catch (Exception exception){}
    }

    public void mute(boolean ismute){
        mRtcEngine.muteAllRemoteAudioStreams(ismute);
    }

    public void setVolume(int volume) {
//        try {
//            mRtcEngine.enableInEarMonitoring(true);
//            mRtcEngine.setInEarMonitoringVolume(volume);
//        }catch (Exception e){}
        try {
            mRtcEngine.adjustPlaybackSignalVolume(volume);
        }catch (Exception exception){}
        try {
            mRtcEngine.adjustAudioMixingPlayoutVolume(volume);
        }catch (Exception exception){}
    }

    /**
     * 继续通话
     * @param token
     * @param roomId
     * @param uid
     * @param iGoonCallback
     */
    public void goonLastCall(String token, String roomId, String uid, IGoonCallback iGoonCallback){
        ChannelMediaOptions options = new ChannelMediaOptions();
        // 设置频道场景为 BROADCASTING。
        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING;
        // 将用户角色设置为 BROADCASTER。
        options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER;
        mRtcEngine.joinChannel(token,roomId,Integer.parseInt(uid),options);
        iGoonCallback.onResult(0);
        com.healthlink.appcloudcalllib.common.Constants.logs.add("成功加入上次通话:"+System.currentTimeMillis());
    }
}
